package com.ktgj.customer.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.ktgj.common.core.annotation.Excel;
import com.ktgj.common.core.enums.AssistProductEnum;
import com.ktgj.common.core.enums.EmHelper;
import com.ktgj.common.core.utils.DateUtils;
import com.ktgj.common.core.utils.SnowFlake;
import com.ktgj.common.redis.service.RedisService;
import com.ktgj.customer.domain.*;
import com.ktgj.customer.domain.dto.CalculationDTO;
import com.ktgj.customer.domain.vo.*;
import com.ktgj.customer.mapper.*;
import com.ktgj.customer.service.*;
import com.ktgj.pay.api.RemotePayService;
import com.ktgj.pay.api.domain.BankCardApi;
import com.ktgj.pay.api.domain.BankPayInfoApi;
import com.ktgj.pay.api.domain.CustomerApi;
import com.ktgj.pay.api.domain.YeeBaoResultApi;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 旅游订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2021-10-26
 */
@Service
public class OrderInfoServiceImpl implements IOrderInfoService
{
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderTouristMapper orderTouristMapper;

    @Autowired
    private OrderPaymentRecord2Mapper orderPaymentRecord2Mapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private LoginServiceImpl loginService;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private ICommonTravelersService commonTravelersService;

    @Autowired
    private IAssistProductService assistProductService;

    @Autowired
    private AssistProductMapper assistProductMapper;

    @Autowired
    private IDepositBusinessService depositBusinessService;

    @Autowired
    private ICouponService couponService;

    @Autowired
    private TravelGroupNumberMapper travelGroupNumberMapper;

    @Autowired
    private ICustomerCardService customerCardService;

    @Autowired
    private IPointRecordService pointRecordService;

    @Autowired
    private ICardService cardService;

    @Autowired
    private PassengerDocumentsMapper passengerDocumentsMapper;

    @Autowired
    private OrderProductMapper orderProductMapper;

    @Autowired
    private RemotePayService remotePayService;

    @Autowired
    private BankCardMapper bankCardMapper;

    @Autowired
    private TravelGroupMapper travelGroupMapper;

    @Autowired
    private IUtilService utilService;

    @Autowired
    private TravelOrderPaymentRecordMapper travelOrderPaymentRecordMapper;

    @Resource
    private TravelOrderRefundMapper travelOrderRefundMapper;

    private static final String TRAVEL = "travel";

    /**
     * 查询旅游订单
     * 
     * @param orderId 旅游订单ID
     * @return 旅游订单
     */
    @Override
    public OrderInfoDto selectOrderInfoById(Long orderId)
    {
        return orderInfoMapper.selectOrderInfoById(orderId);
    }

    /**
     * 查询旅游订单列表
     * 
     * @param orderInfoDto 旅游订单
     * @return 旅游订单
     */
    @Override
    public List<OrderInfoDto> selectOrderInfoList(OrderInfoDto orderInfoDto)
    {
        List<TravelGroupNumberDto>  lstGroupNumber = travelGroupNumberMapper.selectTravelGroupNumberDtoList();
        TravelGroupDto queryTravelGroup = new TravelGroupDto();
        List<TravelGroupDto> lstTravelGroup = travelGroupMapper.selectTravelGroupList(queryTravelGroup);
        List<OrderInfoDto> lstTravelOrder = orderInfoMapper.selectOrderInfoList(orderInfoDto);
        for (OrderInfoDto orderInfo :lstTravelOrder)
        {
            TravelGroupNumberDto travelGroupNumberDto = lstGroupNumber.stream().filter(item -> item.getNumberId().equals(orderInfo.getNumberId())).findFirst().orElse(null);
            if (travelGroupNumberDto != null)
            {
                orderInfo.setGroupName(travelGroupNumberDto.getGroupName());
                orderInfo.setGroupNumber(travelGroupNumberDto.getGroupNumber());
                TravelGroupDto travelGroupDto = lstTravelGroup.stream().filter(item->item.getGroupId().equals(travelGroupNumberDto.getGroupId())).findFirst().orElse(null);
                if (travelGroupDto!=null)
                {
                    orderInfo.setGroupType(travelGroupDto.getCountryType());
                }
                List<OrderTouristDto> lstTourist = orderTouristMapper.selectOrderTouristByOrderId(orderInfo.getOrderId());
                orderInfo.setPersonCount(lstTourist.size());
            }
        }
        return lstTravelOrder;
    }

    /**
     * 新增旅游订单
     * 
     * @param orderInfoDto 旅游订单
     * @return 结果
     */
    @Override
    public int insertOrderInfo(OrderInfoDto orderInfoDto)
    {
        orderInfoDto.setCreateTime(DateUtils.getNowDate());
        return orderInfoMapper.insertOrderInfo(orderInfoDto);
    }

    /**
     * 修改旅游订单
     * 
     * @param orderInfoDto 旅游订单
     * @return 结果
     */
    @Override
    public int updateOrderInfo(OrderInfoDto orderInfoDto)
    {
        return orderInfoMapper.updateOrderInfo(orderInfoDto);
    }

    /**
     * 批量删除旅游订单
     * 
     * @param orderIds 需要删除的旅游订单ID
     * @return 结果
     */
    @Override
    public int deleteOrderInfoByIds(Long[] orderIds)
    {
        return orderInfoMapper.deleteOrderInfoByIds(orderIds);
    }

    /**
     * 删除旅游订单信息
     * 
     * @param orderId 旅游订单ID
     * @return 结果
     */
    @Override
    public int deleteOrderInfoById(Long orderId)
    {
        return orderInfoMapper.deleteOrderInfoById(orderId);
    }

    /**
     * 填写旅游订单
     * @param token
     * @param request
     * @return
     */
    @Override
    public TravelGroupOrderResponse createOrderInfo(String token, TravelGroupOrderRequest request) {
        TravelGroupOrderResponse response = new TravelGroupOrderResponse();
        try {
            Customer loginCustomerByToken = loginService.getLoginCustomerByToken(token);
            Long customerId = loginCustomerByToken.getCustomerId();
            for (PassengerLists passengerList : request.getPassengerLists()) {
                List<CommonPassenger> commonPassengers = commonTravelersService.queryPassengerByCustomerId(customerId, passengerList.getCommonTrvelersId(), passengerList.getCertificateType());
                for (CommonPassenger commonPassenger : commonPassengers) {
                    CheckPassengers checkPassengers = new CheckPassengers();
                    checkPassengers.setId(commonPassenger.getCommonTrvelersId());
                    checkPassengers.setName(commonPassenger.getChineseName());
                    checkPassengers.setTicketType(commonPassenger.getTicketType());
                    checkPassengers.setCardName(commonPassenger.getCertificateName());
                    checkPassengers.setCardId(commonPassenger.getCertificateNumber());
                    response.getCheckPassengersList().add(checkPassengers);
                }
                Customer customer = customerService.selectCustomerById(customerId);
                response.getContact().setName(customer.getCustomerName());
                response.getContact().setPhone(customer.getContractPhoneOne());
                response.getContact().setWx(customer.getWechatId());
            }
            if (request.getEmergencyContact() != null) {
                response.getEmergencyContact().setName(request.getEmergencyContact().getName());
                response.getEmergencyContact().setPhone(request.getEmergencyContact().getPhone());
            }
            //辅营产品
            String status = AssistProductEnum.activation.getValue();
            String businessType = AssistProductEnum.travelgroup.getValue();
            List<AssistProductVo> assistProductVos = assistProductService.queryAssistProductList(status, businessType);
            response.setAssistProductVos(assistProductVos);
            //优惠券
            CouponDto couponDto = couponService.queyUserCoupon(customerId, request.getPrice());
            if (couponDto != null) {
                response.setCouponDto(couponDto);
            }
            //预留款
            BigDecimal aLong = depositBusinessService.queyUserDepositBusiness(customerId);
            response.setDepositBusiness(aLong);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
    }

    /**
     * 生成旅游订单
     * @param token
     * @param input
     * @return
     */
    @Transactional
    @Override
    public TravelGroupOrderOutput createOrder(String token, TravelGroupOrderInput input) throws Exception {
        TravelGroupOrderOutput output = new TravelGroupOrderOutput();
        String orderType = "旅游";
        String orderSourceDesc = "旅游";
        Customer loginCustomerByToken = loginService.getLoginCustomerByToken(token);
        Long customerId = loginCustomerByToken.getCustomerId();
        List<CustomerCard> customerCards = customerCardService.queryCardIdByCustomerId(customerId);

        for (CustomerCard customerCard : customerCards) {
            if (customerCard.getCardId() != null && customerCard.getCardId() != 0){
                Map<String, Object> map = new HashMap<>();
                map.put("cardId", customerCard.getCardId());
                Card card = cardService.selectCardById(customerCard.getCardId());
                if (card != null){
                    customerCard.setCardLevel(card.getCardLevel());
                }
                else {
                    throw new Exception("无效的会员卡");
                }
            }
            else {
                throw new Exception("会员卡没有关联卡id");
            }
        }

        customerCards.sort((y, x) -> Double.compare(y.getCardLevel(), x.getCardLevel()));
        CustomerCard customerCard = customerCards.get(0);

        Long orderID = System.currentTimeMillis() / 1000;
        OrderInfoDto orderInfoDto = new OrderInfoDto();
        orderInfoDto.setOrderId(orderID);
        Long numberId = travelGroupNumberMapper.selectByGroupId(input.getGroupId());
        orderInfoDto.setNumberId(numberId);
        orderInfoDto.setCustomerId(customerId);
        orderInfoDto.setCustomerName(loginCustomerByToken.getCustomerName());
        orderInfoDto.setCustomerPhone(loginCustomerByToken.getContractPhoneOne());
        if (customerCard != null) {
            orderInfoDto.setCustomerCardId(customerCard.getCardCode());
        }
        orderInfoDto.setWechatId(loginCustomerByToken.getWechatId());
        orderInfoDto.setPayAmount(input.getPayAmount());
        orderInfoDto.setEmployeeId(999L);
//        String status = AssistProductEnum.activation.getValue();
//        String businessType = AssistProductEnum.travelgroup.getValue();
//        List<AssistProductVo> assistProductVos = assistProductService.queryAssistProductList(status, businessType);
//        for (AssistProductVo assistProductVo : assistProductVos) {
        BigDecimal price = new BigDecimal(0);
        for (Long aLong : input.getAssistId()) {
            BigDecimal decimal = assistProductMapper.queryAssistById(aLong);
            price = price.add(decimal);
        }
        orderInfoDto.setTotalProductAmount(price.multiply(new BigDecimal(input.getPassengerLists().size())));
//        }
        //orderInfoDto.setTotalPlusUsed();
        if (input.getCouponId() != null && input.getCouponId() != 0) {
            orderInfoDto.setCouponID(input.getCouponId());
            Coupon coupon = couponService.couponById(input.getCouponId());
            if (coupon.getCouponType().equals("CouponTypeFullMinus") || coupon.getCouponType().equals("CouponTypeCashCoupon")) {
                orderInfoDto.setTotalDiscountUsed(new BigDecimal(coupon.getCouponPrice()));
            } else {
                BigDecimal couponDiscount = new BigDecimal(coupon.getCouponDiscount());
                BigDecimal divide = couponDiscount.divide(new BigDecimal(100));
                BigDecimal multiply = input.getTotalPrice().multiply(divide);
                BigDecimal subtract = input.getTotalPrice().subtract(multiply);
                orderInfoDto.setTotalDiscountUsed(subtract);
            }
        }
        if (input.getUsedDeposit() != null) {
            orderInfoDto.setDepositAmount(input.getUsedDeposit());
        }
        //orderInfoDto.setTotalTravelUsed();
        orderInfoDto.setCreateTime(new Date());
        orderInfoMapper.insertOrderInfo(orderInfoDto);
        for (PassengerLists passengerList : input.getPassengerLists()) {
            List<CommonPassenger> commonPassengers = commonTravelersService.queryPassengerByCustomerId(customerId, passengerList.getCommonTrvelersId(), passengerList.getCertificateType());
            for (CommonPassenger commonPassenger : commonPassengers) {
                OrderTouristDto orderTouristDto = new OrderTouristDto();
                Long touristId = System.currentTimeMillis() / 1000;
                orderTouristDto.setTouristId(touristId);
                orderTouristDto.setOrderId(orderID);
                orderTouristDto.setTouristName(commonPassenger.getChineseName());
                orderTouristDto.setTouristCardNo(commonPassenger.getCertificateNumber());
                orderTouristDto.setTouristCardType(commonPassenger.getCertificateType());
                //orderTouristDto.setTouristBirthday();
                //orderTouristDto.setTouristSex();
                orderTouristDto.setPhone(commonPassenger.getDomesticPhone());
                //orderTouristDto.setAgeType();
                //orderTouristDto.setStartCity();
                //orderTouristDto.setReturnCity();
                //orderTouristDto.setRoomType();
                //orderTouristDto.setDifferentRoomFee();
                //orderTouristDto.setFlightFee();
                //orderTouristDto.setIsBuyCard();
                //orderTouristDto.setBuyCardTypeId();
                //orderTouristDto.setBuyCardFee();
                //orderTouristDto.setTripNumberType();
                //orderTouristDto.setTripNumber();
                //orderTouristDto.setTripNumberFee();
                //orderTouristDto.setPlusUsedType();
                //orderTouristDto.setPlusUsed();
                //orderTouristDto.setTravelUsedType();
                //orderTouristDto.setDiscountUsed();
                //orderTouristDto.setTravelUsed();
                orderTouristDto.setStatus("0");
                orderTouristDto.setGroupFee(Long.valueOf(input.getGroupPrice().toString()));
                //orderTouristDto.setIsRenewCard();
                //orderTouristDto.setRenewCardTypeId();
                //orderTouristDto.setRenewFee();
                orderTouristDto.setCreateTime(orderInfoDto.getCreateTime());
                orderTouristMapper.insertOrderTourist(orderTouristDto);
            }
        }
        if (input.getCouponId() != null || (input.getUsedDeposit() != null && input.getUsedDeposit().longValue() > 0L)) {
            pointRecordService.spend(customerId, 0L, orderType, orderInfoDto.getOrderId(), orderSourceDesc, input.getCouponId(), 1L);
        }
        redisService.setCacheObject(TRAVEL + customerId, JSON.toJSON(orderInfoDto), 30L, TimeUnit.MINUTES);
        output.setOrderId(orderInfoDto.getOrderId());
        output.setCreateTime(orderInfoDto.getCreateTime().toString());
        return output;
    }

    @Override
    public int travelOrderRefund(Long orderId)
    {
        TravelOrderRefund queryOrderRefund = travelOrderRefundMapper.selectTravelOrderRefundByOrderId(orderId);
        if (queryOrderRefund != null)
        {
            return 0;
        }
        OrderInfoDto orderInfoDto = orderInfoMapper.selectOrderInfoById(orderId);
        orderInfoDto.setStatus(1);
        orderInfoMapper.updateOrderInfo(orderInfoDto);
        TravelGroupNumberDto travelGroupNumberDto = travelGroupNumberMapper.selectTravelGroupNumberById(orderInfoDto.getNumberId());
        TravelOrderRefund travelOrderRefund = new TravelOrderRefund();
        travelOrderRefund.setCustomerId(orderInfoDto.getCustomerId());
        travelOrderRefund.setCustomerName(orderInfoDto.getCustomerName());
        travelOrderRefund.setGroupName(travelGroupNumberDto.getGroupName());
        travelOrderRefund.setOrderId(orderInfoDto.getOrderId());
        travelOrderRefund.setRefundamount(orderInfoDto.getPayAmount());
        travelOrderRefund.setRefundstatus(0l);
        travelOrderRefund.setApplytime(new Date());
        travelOrderRefund.setCustomerPhone(orderInfoDto.getCustomerPhone());
        return travelOrderRefundMapper.insertTravelOrderRefund(travelOrderRefund);
    }

    /**
     * 获取待支付订单
     * @param customerId
     * @return
     */
    @Override
    public List<OrderInfoDto> queryByPayOrder(Long customerId) {
        List<OrderInfoDto> orderInfoDtoList = new ArrayList<>();
        Collection<String> keys = redisService.keys("order" + customerId + "t*");
        for (String key : keys) {
            JSONObject jsonObject = redisService.getCacheObject(key);
            OrderInfoDto orderInfoDto = jsonObject.toJavaObject(OrderInfoDto.class);
            orderInfoDtoList.add(orderInfoDto);
        }
        return orderInfoDtoList;
    }

    /**
     * 旅游创建订单
     * */
    @Override
    public String travelOrder(HttpServletRequest request, TravelOrderInfoVo travelOrderInfoVo) throws Exception {
        //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String orderNumber = "";
        String token = request.getHeader("token");
        if (token != null && !token.equals("")){
            Customer customer = loginService.getLoginCustomerByToken(token);
            CustomerIdVo customerIdVo = new CustomerIdVo();
            customerIdVo.setCustomerId(customer.getCustomerId());
            CustomerIdVo tmpCustomerIdVo = customerService.customerId(customerIdVo);

            //辅营产品信息
            List<BigDecimal> additionalList = new ArrayList<>();
            if (travelOrderInfoVo.getAuxiliaryProductsIdList() != null && travelOrderInfoVo.getAuxiliaryProductsIdList().size() > 0) {
                for (Long id : travelOrderInfoVo.getAuxiliaryProductsIdList()) {
                    AssistProduct assistProduct = assistProductService.queryAssistProduct(id);
                    BigDecimal salePrice = assistProduct.getSalePrice();
                    additionalList.add(salePrice);
                }
            }

            //金币
            BigDecimal depositSkipPwdAmount = depositBusinessService.queyUserDepositBusiness(customer.getCustomerId());
            //积分
            Long pntValue = pointRecordService.queryUserCreditsNum(customer.getCustomerId());

            CalculationVO calculationVOApi = new CalculationVO();
            List<BigDecimal> unitPriceList = new ArrayList<>();
            //获取旅游团详情
            TravelGroup travelGroup = travelGroupMapper.selectTravelGroup(travelOrderInfoVo.getNumberIdList().get(0));
            for (int i = 0; i < travelOrderInfoVo.getIdList().size(); i++) {
                if (tmpCustomerIdVo.getLevel().equals("1"))
                    unitPriceList.add(travelGroup.getGroupFee());
                else
                    unitPriceList.add(travelGroup.getVipGroupFee());
            }
            calculationVOApi.setPrices(unitPriceList);//商品单价集合
            calculationVOApi.setAmount(1);//商品数量
            calculationVOApi.setAdditionalPrices(additionalList);//附加商品单价集合
            calculationVOApi.setAdditionalAmount(travelOrderInfoVo.getIdList().size());//附加商品数量
            calculationVOApi.setCouponId(travelOrderInfoVo.getCouponId());//优惠卷id
            calculationVOApi.setDepositAmount(depositSkipPwdAmount);//用户拥有的金币数量
            calculationVOApi.setUseDeposit(travelOrderInfoVo.isUseDeposit());//是否使用金币
            if (pntValue != null) {
                calculationVOApi.setPointAmount(Integer.parseInt(pntValue.toString()));//用户拥有的积分数量
            } else {
                calculationVOApi.setPointAmount(0);
            }
            calculationVOApi.setUsePoint(travelOrderInfoVo.isUsePoint());//是否使用积分
            CalculationDTO calculationDTO = utilService.calculation(calculationVOApi);
            BigDecimal couponAmount = calculationDTO.getPrice();
            BigDecimal payAmount = new BigDecimal(travelOrderInfoVo.getPayAmount());
            if (couponAmount.compareTo(payAmount) != 0) {
                throw new Exception("支付价格出现变动");
            }

            //创建订单
            if (customer != null){
                SnowFlake snowFlake = new SnowFlake(11, 11);
                Long orderNum = snowFlake.nextId();
                orderNumber = String.valueOf(orderNum);

                Long orderId = System.currentTimeMillis() / 1000;
                OrderInfoDto orderInfoDto = new OrderInfoDto();
                orderInfoDto.setUrgentPhone(travelOrderInfoVo.getUrgentPhone());
                orderInfoDto.setOrderId(orderId);
                orderInfoDto.setOrderNum(orderNum.toString());
                orderInfoDto.setNumberId(travelOrderInfoVo.getNumberIdList().get(0));
                orderInfoDto.setCustomerId(customer.getCustomerId());
                orderInfoDto.setCustomerName(customer.getCustomerName());
                orderInfoDto.setCustomerPhone(customer.getContractPhoneOne());
                orderInfoDto.setCustomerCardId(tmpCustomerIdVo.getCustomerCard());
                orderInfoDto.setWechatId(travelOrderInfoVo.getWechatId());
                orderInfoDto.setStatus(0);
                if (travelOrderInfoVo.getPayAmount() != null && !travelOrderInfoVo.getPayAmount().equals("")){
                    // TODO 测试 后期放开价格 orderInfoDto.setPayAmount(new BigDecimal(travelOrderInfoVo.getPayAmount()));
                    orderInfoDto.setPayAmount(new BigDecimal(0.1));
                }

                orderInfoDto.setPayStatus(EmHelper.OrderStatus.Unpaid.getValue());
                orderInfoDto.setEmployeeId(1L);
                orderInfoDto.setOrderMemo(travelOrderInfoVo.getOrderMemo());

                try {
                    orderInfoDto.setCreateTime(new Date());
                } catch (Exception e){
                    throw new Exception("日期格式错误");
                }
                int i = orderInfoMapper.insertOrderInfo(orderInfoDto);
                if (i > 0){
                    //新增支付信息
                    TravelOrderPaymentRecord orderPaymentRecord = new TravelOrderPaymentRecord();
                    orderPaymentRecord.setPayAmount(orderInfoDto.getPayAmount());
                    orderPaymentRecord.setCreateTime(new Date());
                    orderPaymentRecord.setPayStatus(EmHelper.OrderStatus.Unpaid.getValue());
                    orderPaymentRecord.setOrderId(orderId);
                    travelOrderPaymentRecordMapper.insertTravelOrderPaymentRecord(orderPaymentRecord);

                    for (String aLong : travelOrderInfoVo.getIdList()) {
                        String travelerId = aLong.substring(0, aLong.indexOf(","));
                        String documentsId = aLong.substring(aLong.indexOf(",") + 1);
                        CommonTravelers commonTravelers = commonTravelersService.selectCommonTravelersById(Long.valueOf(travelerId));
                        PassengerDocuments passengerDocuments = passengerDocumentsMapper.backSelectDocumentsById(Long.valueOf(documentsId));
                        if (commonTravelers != null && passengerDocuments != null){
                            OrderTouristDto orderTourist = new OrderTouristDto();
                            orderTourist.setOrderId(orderId);
                            orderTourist.setTouristName(commonTravelers.getChineseName());
                            orderTourist.setTouristCardNo(passengerDocuments.getCertificateNumcer());
                            orderTourist.setTouristCardType(passengerDocuments.getCertificateType());
                            orderTourist.setTouristBirthday(commonTravelers.getDateOfBirth());
                            orderTourist.setTouristSex(commonTravelers.getGender());
                            orderTourist.setPhone(commonTravelers.getDomesticPhone());
                            orderTourist.setAgeType(commonTravelers.getTicketType());
                            orderTourist.setStartCity(travelOrderInfoVo.getStartCity());
                            orderTourist.setReturnCity(travelOrderInfoVo.getReturnCity());
                            orderTourist.setStatus(EmHelper.OrderStatus.Unpaid.getValue());
                            int tourist = orderTouristMapper.insertOrderTourist(orderTourist);
                            if (tourist > 0){
                                if (travelOrderInfoVo.getAuxiliaryProductsIdList().size() > 0){
                                    for (Long auxiliaryProductsId : travelOrderInfoVo.getAuxiliaryProductsIdList()) {
                                        AssistProduct assistProduct = assistProductMapper.selectProduct(auxiliaryProductsId);
                                        if (assistProduct != null){
                                            OrderProduct orderProduct = new OrderProduct();
                                            orderProduct.setProductName(assistProduct.getName());
                                            orderProduct.setOrderId(orderId);
                                            orderProduct.setTouristId(orderTourist.getTouristId());
                                            orderProduct.setProductId(auxiliaryProductsId);
                                            orderProduct.setSalePrice(assistProduct.getSalePrice());
                                            orderProduct.setStatusId(EmHelper.OrderStatus.UnTakeEffect.getValue());
                                            int product = orderProductMapper.insertOrderProduct(orderProduct);
                                            if (product <= 0){
                                                throw new Exception("创建旅游辅营产品失败");
                                            }
                                        }
                                        else {
                                            throw new Exception(auxiliaryProductsId + "不可用");
                                        }
                                    }
                                }
                            }
                            else {
                                throw new Exception("旅客添加失败" + aLong);
                            }
                        }
                        else {
                            throw new Exception(aLong + "不可用");
                        }
                    }
                }
                else {
                    throw new Exception("旅游订单创建失败" + travelOrderInfoVo.getNumberIdList().get(0));
                }
            }
            else {
                throw new Exception("登录已过期");
            }
        }
        else {
            throw new Exception("token不能为空");
        }
        return orderNumber;
    }

    /**
     * 旅游支付
     * */
    @Override
    public String orderInfoPay(HttpServletRequest request, OrderInfoPayVo orderInfoPayVo) throws Exception {
        String token = request.getHeader("token");
        Customer customer = loginService.getLoginCustomerByToken(token);
        if (customer == null){
            throw new Exception("会员信息获取失败");
        }

        /*CalculationVO calculationVO = new CalculationVO();
        List<BigDecimal> prices = new ArrayList<>();
        prices.add(new BigDecimal(orderInfoPayVo.getAmout()));
        calculationVO.setPrices(prices);//商品单价集合
        calculationVO.setAmount(1);//商品数量
        List<BigDecimal> additionalPrices = new ArrayList<>();
        if (orderInfoPayVo.getIds() != null && orderInfoPayVo.getIds().size() > 0){
            for (Long id : orderInfoPayVo.getIds()) {
                AssistProduct assistProduct = assistProductMapper.selectProduct(id);
                if (assistProduct != null){
                    additionalPrices.add(assistProduct.getSalePrice());
                }
                else {
                    throw new Exception("没有" + id + "产品");
                }
            }
        }

        calculationVO.setAdditionalPrices(additionalPrices);//附加商品单价集合
        calculationVO.setAdditionalAmount(orderInfoPayVo.getIds().size());//附加商品数量
        calculationVO.setCouponId(orderInfoPayVo.getCouponId());//优惠卷id

        BigDecimal bigDecimal = depositBusinessService.queyUserDepositBusiness(customer.getCustomerId());
        if (bigDecimal.compareTo(new BigDecimal(0)) == 0){
            bigDecimal = new BigDecimal(0);
        }

        calculationVO.setDepositAmount(bigDecimal);//用户拥有的金币数量
        calculationVO.setUseDeposit(orderInfoPayVo.isUseDeposit());//是否使用金币

        Long creditsNum = pointRecordService.queryUserCreditsNum(customer.getCustomerId());
        //用户拥有的积分数量
        if (creditsNum == null || creditsNum == 0)
        {
            calculationVO.setPointAmount(0);
        }else {
            calculationVO.setPointAmount(Integer.valueOf(creditsNum.toString()));
        }
        calculationVO.setUsePoint(orderInfoPayVo.isUsePoint());//是否使用积分
        CalculationDTO calculation = utilService.calculation(calculationVO);
        if (calculation.getPrice().compareTo(new BigDecimal(orderInfoPayVo.getAmout())) != 0){
            throw new Exception("支付价格出现变动");
        }*/

        //获取订单信息
        OrderInfoDto orderInfoDto = orderInfoMapper.selectOrderInfoByOrderNum(Long.valueOf(orderInfoPayVo.getOrderId()));
        if (orderInfoPayVo.getPayType() != null && !orderInfoPayVo.getPayType().equals("")){
            CustomerApi customerApi = new CustomerApi();
            BeanUtils.copyProperties(customer, customerApi);
            BankCardApi card = new BankCardApi();
            BankCard bankCard = bankCardMapper.selectBankCardById(Long.valueOf(orderInfoPayVo.getCardId()));
            BeanUtils.copyProperties(bankCard, card);

            //支付信息
            BankPayInfoApi bankPayInfoApi = new BankPayInfoApi();
            bankPayInfoApi.setJsjOrderId(orderInfoPayVo.getOrderId());
            bankPayInfoApi.setMoneyAmout(String.valueOf(orderInfoDto.getPayAmount()));
            bankPayInfoApi.setCustomer(customerApi);
            bankPayInfoApi.setCard(card);
            bankPayInfoApi.setPayType(orderInfoPayVo.getPayWay());
            YeeBaoResultApi yeeBaoResultApi = null;

            if (orderInfoPayVo.getPayType().equals(EmHelper.cardType.CREDIT_CARD.getValue())){
                //信用卡
                yeeBaoResultApi = remotePayService.CreditSale(bankPayInfoApi);
            } else if (orderInfoPayVo.getPayType().equals(EmHelper.cardType.DEBIT_CARD.getValue())) {
                //借记卡
                yeeBaoResultApi = remotePayService.DebitSale(bankPayInfoApi);
            }
            TravelOrderPaymentRecord orderPaymentRecord = travelOrderPaymentRecordMapper.queryTravelOrderPaymentRecordByOrderId(orderInfoDto.getOrderId());
            if (yeeBaoResultApi.getCode().equals("1")) {
                orderPaymentRecord.setPayStatus(EmHelper.OrderStatus.Paid.getValue());
                orderPaymentRecord.setTradeNo(yeeBaoResultApi.getTrxId());
                orderPaymentRecord.setTradeTime(new Date());
                orderPaymentRecord.setPayMethod(orderInfoPayVo.getPayType());
                travelOrderPaymentRecordMapper.updateTravelOrderPaymentRecord(orderPaymentRecord);

                orderInfoDto.setPayStatus(EmHelper.OrderStatus.Paid.getValue());
                orderInfoMapper.updateOrderInfo(orderInfoDto);
                return "支付成功";
            } else {
                orderPaymentRecord.setPayStatus(EmHelper.OrderStatus.failPay.getValue());
                orderPaymentRecord.setTradeTime(new Date());
                orderPaymentRecord.setPayMethod(orderInfoPayVo.getPayType());
                travelOrderPaymentRecordMapper.updateTravelOrderPaymentRecord(orderPaymentRecord);

                orderInfoDto.setPayStatus(EmHelper.OrderStatus.failPay.getValue());
                orderInfoMapper.updateOrderInfo(orderInfoDto);
                return "支付失败";
            }
        }
        else {
            throw new Exception("支付类型不能为空");
        }
    }
}
